import { QuestionItemType } from '@/components/question/typing';
import { theme } from 'ant-design-vue';
import { computed, defineComponent, onMounted, PropType, ref } from 'vue';
import './style.css';

export default defineComponent({
  props: {
    questionItem: Object as PropType<QuestionItemType>,
  },
  emits: ['mouseenter', 'mouseleave', 'click'],
  setup(props, { emit }) {
    const { questionItem } = props;
    const scaleNodeRef = ref<any>(null);
    const canvasRef = ref();
    const itemTitleRef = ref();
    const itemTitleWidth = ref(0);
    const { token } = theme.useToken();

    const onMouseenter = () => {
      emit('mouseenter', questionItem);
    };

    const onMouseleave = () => {
      emit('mouseleave');
    };
    const onClick = () => {
      emit('click', questionItem);
    };

    const getStringWidth = (text: any, style: any) => {
      const context = canvasRef.value.getContext('2d');
      context.font = style.font;
      return context.measureText(text).width;
    };

    onMounted(() => {
      const itemTitleStyle = window.getComputedStyle(itemTitleRef.value);
      itemTitleWidth.value = Math.ceil(getStringWidth(questionItem?.title, itemTitleStyle)) + 6;
    });

    const scaleItemTitleWidth = computed(() => {
      return itemTitleWidth.value < 80 ? 80 : itemTitleWidth.value;
    });

    return () => {
      return (
        <>
          <canvas ref={canvasRef} width={0} height={0} />
          <div
            class="scale-node-container"
            ref={scaleNodeRef}
            onMouseenter={onMouseenter}
            onMouseleave={onMouseleave}
            onClick={onClick}
          >
            <div
              class="scale-item-title"
              ref={itemTitleRef}
              style={{ width: `${scaleItemTitleWidth.value}px` }}
            >
              {questionItem?.title}
            </div>
            <div class="scale-item-graph-container">
              <div
                class="scale-item-graph-line"
                style={{
                  borderColor:
                    questionItem?.isHovered === true
                      ? token.value.colorPrimary
                      : token.value.colorBorder,
                }}
              ></div>
              <div
                class="scale-item-graph-cirular"
                style={{
                  left: `${(scaleItemTitleWidth.value - 16) / 2}px`,
                  borderColor:
                    questionItem?.isHovered === true
                      ? token.value.colorPrimary
                      : token.value.colorBorder,
                }}
              ></div>
            </div>
            <div class="scale-item-value">
              {questionItem?.isIndividual ? '' : questionItem?.value}
            </div>
          </div>
        </>
      );
    };
  },
});
